package com.wm.blog_search.service;

import com.alibaba.fastjson.JSON;
import com.wm.blog_common.result.Result;
import com.wm.blog_config.Document.BlogDocument;
import com.wm.blog_search.repository.BlogDocumentRepository;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;

/**
 * @author 半卷流年
 * @date 2020-5-22 18:15
 */
@Service
@Slf4j
@AllArgsConstructor
public class BlogSearchServiceImpl extends BaseSearchServiceImpl<BlogDocument>{

    private final ElasticsearchTemplate elasticsearchTemplate;

    private final BlogDocumentRepository blogDocumentRepository;

    /**
     * 保存文档
     * @param productDocuments
     */
    public Result save(BlogDocument ... productDocuments) {
        elasticsearchTemplate.putMapping(BlogDocument.class);
        if(productDocuments.length > 0){
            log.info("【保存索引】：{}", JSON.toJSONString(blogDocumentRepository.saveAll(Arrays.asList(productDocuments))));
            return Result.success();
        }
        return Result.failure();
    }

    /**
     * 删除文档
     * @param id
     */
    public Result delete(Long id) {
        blogDocumentRepository.deleteById(id);
        return Result.success();
    }

    /**
     * 删除索引的文档
     */
    public Result deleteAll() {
        blogDocumentRepository.deleteAll();
        return Result.success();
    }

    /**
     * id查询文档
     * @param id
     * @return
     */
    public Result getById(Long id) {
        BlogDocument document = Optional.ofNullable(blogDocumentRepository.findById(id).get()).orElse(new BlogDocument());
        return Result.success(document);
    }

    /**
     * 查询所有的文档
     * @return
     */
    public Result getAll() {
        List<BlogDocument> list = new ArrayList<>();
        blogDocumentRepository.findAll().forEach(list::add);
        return Result.success(list);
    }

}
